package edu.aynu.cyloc.service.impl;

import edu.aynu.cyloc.entity.User;
import edu.aynu.cyloc.service.SendRequestService;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


/**
 * @Author: haha
 * @Date: 2021/9/26 21:53
 * @Description:
 */
@Service
@Slf4j
public class SendRequestServiceImpl implements SendRequestService {


    @Value("${hnydws.loginUrl}")
    private String url;


    @Override
    public boolean sendRequest(User user) {
        MultiValueMap<String, String> map = new HttpHeaders();
        map.add("Number", user.getSno());
        map.add("Name", user.getName());
        map.add("nj", user.getGrade().toString());
        map.add("xy", user.getCollegeId().toString());
        map.add("dzb", user.getClassId().toString());
        map.add("date", String.valueOf(System.currentTimeMillis()));
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("X-Requested-With", "XMLHttpRequest");
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);
        ResponseEntity<Result> response = client.exchange(url, method,requestEntity, Result.class);
        Result body = response.getBody();
        log.info("sno:{},name:{},body:{}", user.getSno(), user.getName(), body);
        if (body.getCode() == 0) {
            user.setStudy(true);
            user.updateById();
            return true;
        }
        return false;
    }

    @Data
    @ToString
    static class Result {
        private int code;
        private String msg;
    }
}
